﻿using System;
using System.Security.Principal;
using System.Web.Security;

namespace VASJ.Model
{
    public class MembershipHelper
    {
        public static void CreateUser(string username, string password, string email)
        {
            try
            {
                string m_Message = string.Empty;
                var existUser = Membership.GetUser(username);
                if (existUser == null)
                {
                    MembershipUser user = Membership.CreateUser(username, password, email);
                }
                else
                {
                    m_Message = "The user with the same UserName already exists!";
                }
            }
            catch (System.Exception ex)
            {
                Logger.Log.Fatal("Unable to create default roles");
                Logger.Log.Fatal(ex.Message);
            }
        }

        public static void CreateUser(string username, string password, string email, string question, string answer)
        {
            try
            {
                string m_Message = string.Empty;
                MembershipCreateStatus createStatus;
                var existUser = Membership.GetUser(username);
                if (existUser == null)
                {
                    MembershipUser user = Membership.CreateUser(username, password, email, question, answer, true, out createStatus);
                    switch (createStatus)
                    {
                        //This Case Occured whenver User Created Successfully in database
                        case MembershipCreateStatus.Success:
                            m_Message = "The user account was successfully created";
                            break;
                        // This Case Occured whenver we send duplicate UserName
                        case MembershipCreateStatus.DuplicateUserName:
                            m_Message = "The user with the same UserName already exists!";
                            break;
                        //This Case Occured whenver we give duplicate mail id
                        case MembershipCreateStatus.DuplicateEmail:
                            m_Message = "The user with the same email address already exists!";
                            break;
                        //This Case Occured whenver we send invalid mail format
                        case MembershipCreateStatus.InvalidEmail:
                            m_Message = "The email address you provided is invalid.";
                            break;
                        //This Case Occured whenver we send empty data or Invalid Data
                        case MembershipCreateStatus.InvalidAnswer:
                            m_Message = "The security answer was invalid.";
                            break;
                        // This Case Occured whenver we supplied weak password
                        case MembershipCreateStatus.InvalidPassword:
                            m_Message = "The password you provided is invalid. It must be 7 characters long and have at least 1 special character.";
                            break;
                        default:
                            m_Message = "There was an unknown error; the user account was NOT created.";
                            break;
                    }
                }
                else
                {
                    m_Message = "The user with the same UserName already exists!";
                }
            }
            catch (System.Exception ex)
            {
                Logger.Log.Fatal("Unable to create default roles");
                Logger.Log.Fatal(ex.Message);
            }
        }

        public static void CreateRoles()
        {
            try
            {
                string newRoles = System.Configuration.ConfigurationManager.AppSettings["KeToanRoles"];
                if (newRoles == null)
                    return;

                foreach (string tmp in newRoles.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    string role = tmp.Trim();
                    if (Roles.RoleExists(role))
                        continue;

                    Roles.CreateRole(role);
                }
            }
            catch (System.Exception ex)
            {
                Logger.Log.Fatal("Unable to create default roles");
                Logger.Log.Fatal(ex.Message);
            }
        }

        public static void CreateAdmin()
        {
            try
            {
                string adminUsername = System.Configuration.ConfigurationManager.AppSettings["KeToanAdmin"];

                if (Membership.GetUser(adminUsername) == null)
                {
                    string[] roles = Roles.GetAllRoles();
                    if (roles.Length == 0)
                        return;
                    MembershipCreateStatus status;
                    Membership.CreateUser(adminUsername, adminUsername, "nvm@aod.vn", null, null, true, out status);

                    if (status == MembershipCreateStatus.Success)
                    {
                        //SaveProfile(adminUsername, adminUsername, "nvm@aod.vn", string.Empty, string.Empty);

                        foreach (var role in roles)
                            Roles.AddUserToRole(adminUsername, role);
                    }
                }

                //for (var i = 0; i < 150; i++)
                //{
                //    var userName = string.Concat(adminUsername, i);
                //    var email = "support" + i + "@gmail.com";

                //    MembershipCreateStatus status;
                //    Membership.CreateUser(userName, userName, email, null, null, true, out status);

                //    if (status == MembershipCreateStatus.Success)
                //        SaveProfile(userName, userName, email, string.Empty, string.Empty);
                //}
            }
            catch (System.Exception ex)
            {
                Logger.Log.Fatal("Unable to create default admin");
                Logger.Log.Fatal(ex.Message);
            }
        }

        public static Guid GetUserId(IPrincipal user)
        {
            MembershipUser member = Membership.GetUser(user.Identity.Name);
            string guidString = member.ProviderUserKey.ToString();
            Guid guid = new Guid(guidString);
            return guid;
        }

        public static Guid? GetUserId(string username)
        {
            MembershipUser member = Membership.GetUser(username);
            if (member != null)
            {
                try
                {
                    string guidString = member.ProviderUserKey.ToString();
                    Guid guid = new Guid(guidString);
                    return guid;
                }
                catch (Exception ex)
                {
                    Logger.Log.Fatal("Unable to get user");
                    Logger.Log.Fatal(ex.Message);
                }
            }
            return null;
        }

        public static void SaveProfile(string userName, string fullName, string email, string phone, string organization)
        {
            var p = ProfileHelper.GetProfile(userName);
            p.KeToanProfile = new KeToanProfile(fullName, email, phone, organization);
            p.Save();
        }

        public static bool IsUserInRoleOnly(string user, string role)
        {
            string[] roles = Roles.GetRolesForUser(user);
            if (roles.Length == 1 && roles[0] == role)
            {
                return true;
            }
            return false;
        }

        public static bool IsUserInRoleOnly(IPrincipal user, string role)
        {
            return IsUserInRoleOnly(user.Identity.Name, role);
        }

        public static bool IsReader(IPrincipal user)
        {
            return IsUserInRoleOnly(user.Identity.Name, KeToanRoles.KeToanReader);
        }

        public static bool IsReader(string user)
        {
            return IsUserInRoleOnly(user, KeToanRoles.KeToanReader);
        }

        public static bool IsEditor(IPrincipal user)
        {
            return IsUserInRoleOnly(user.Identity.Name, KeToanRoles.KeToanEditor);
        }

        public static bool IsEditor(string user)
        {
            return IsUserInRoleOnly(user, KeToanRoles.KeToanEditor);
        }

        public static bool IsAdmin(IPrincipal user)
        {
            return Roles.IsUserInRole(user.Identity.Name, KeToanRoles.KeToanAdmin);
        }

        public static bool IsAdmin(string user)
        {
            return Roles.IsUserInRole(user, KeToanRoles.KeToanAdmin);
        }

        public static void Unlock(string user)
        {
            try
            {
                //Check to see if the current user exists
                if (Membership.GetUser(user) != null)
                {
                    //Check to see if the user is currently locked out
                    if (Membership.GetUser(user).IsLockedOut)
                    {
                        /*

                        //Get the last lockout  date from the user
                        DateTime lastLockout = Membership.GetUser(user).LastLockoutDate;

                        //Calculate the time the user should be unlocked
                        DateTime unlockDate = lastLockout.AddMinutes(Membership.PasswordAttemptWindow);

                        //Check to see if it is time to unlock the user
                        if (DateTime.Now > unlockDate)
                            Membership.GetUser(user).UnlockUser();*/

                        //Unlock by administrator not waiting
                        Membership.GetUser(user).UnlockUser();
                    }
                }
            }
            catch (System.Exception ex)
            {
                Logger.Log.Fatal("Unable to unlock user");
                Logger.Log.Fatal(ex.Message);
            }
        }
    }
}